package com.tmsps.common.filter;

import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

public class AddResponseHeaderFilter extends OncePerRequestFilter {

	/**
	 * 头部配置
	 */
	private Map<String, String>	headerMap = null;

	public AddResponseHeaderFilter(){ }

	public AddResponseHeaderFilter(Map<String, String> headerMap){
		this.headerMap = headerMap;
	}

	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
			throws ServletException, IOException {

	    setDefaultHeader(response);

		// 配置 cookie 开启 httponly,Secure
		response.setHeader("SET-COOKIE", "JSESSIONID=" + request.getSession().getId() + ";Secure;HttpOnly;");

		// 使用配置文件来盖默认项
		if(headerMap != null) {
			for (String key : headerMap.keySet()) {
				response.setHeader(key, headerMap.get(key));
			}
		}

		filterChain.doFilter(request, response);
	}


	/**
	 * 设置默认的响应头头
	 */
	private void setDefaultHeader(HttpServletResponse response) {
		response.addHeader("x-frame-options","SAMEORIGIN");
		// 阻止浏览器进行content-type 嗅探。
		response.setHeader("X-Content-Type-Options","nosniff");
		response.setHeader("Content-Security-Policy", "script-src 'self' cdn.sxnuoyun.com 'unsafe-inline' 'unsafe-eval' blob: data: ;");
		response.setHeader("X-Xss-Protection", "1;mod=block");
	}
}
